package com.ztc.util;

import java.math.BigDecimal;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 *
 * @author :yyzh <br>
 * @description :数字转换类 <br>
 * @file_name :NumberUitl.java <br>
 * @system_name :car-util <br>
 * @创建时间 :2016年4月12日 下午3:10:35
 */
public class NumberUitl {
    public static final BigDecimal ONE_BAI=new BigDecimal("100");
    public static Integer parseInt(String str) {
        return parseInt(str, null);
    }

    public static Integer parseInt(String str, Integer defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Long parseLong(String str) {
        return parseLong(str, null);
    }

    public static Long parseLong(String str, Long defaultValue) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Double parseDouble(String str) {
        return parseDouble(str, null);
    }

    public static Double parseDouble(String str, Double defaultValue) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Float parseFloat(String str) {
        return parseFloat(str, null);
    }

    public static Float parseFloat(String str, Float defaultValue) {
        try {
            return Float.parseFloat(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Number parse(Object obj, Number defaultValue) {
        if (!isNumeric(obj)) {
            return defaultValue;
        }
        if (defaultValue instanceof Integer) {
            return Integer.parseInt(String.valueOf(obj));
        } else if (defaultValue instanceof Long) {
            return Long.parseLong(String.valueOf(obj));
        } else if (defaultValue instanceof Double) {
            return Double.parseDouble(String.valueOf(obj));
        } else if (defaultValue instanceof Float) {
            return Float.parseFloat(String.valueOf(obj));
        } else {
            return defaultValue;
        }
    }

    public static boolean isNumeric(Object obj) {
        if (obj instanceof Number) {
            return true;
        } else if (obj instanceof String) {
            String cs = (String) obj;
            if (cs == null || cs.length() == 0) {
                return false;
            }
            int sz = cs.length();
            for (int i = 0; i < sz; i++) {
                if (!Character.isDigit(cs.charAt(i))) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
